<?php
namespace App\Services\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

use App\Models\AdminUser;
use App\Models\Role as RoleModel;
use Illuminate\Support\Facades\Log;

class AdminUserService extends \App\Services\ComService
{
    /**
     * 获取所有普通会员的数据
     * @param Request $request
     * @return mixed
     */
    public function getAdminUser(Request $request){
        $perPage = $request->input('perPage', 20);
        $whereParameter[] = [
            'is_administrator', '=', 0
        ];
        //搜索
        $searchData = $request->input('search');
        if(!empty($searchData)){
            isset($searchData['status']) && $whereParameter[] = [
                'status', '=', $searchData['status']
            ];
            isset($searchData['phone']) && $whereParameter[] = [
                'phone', 'like', $searchData['phone'] . '%'
            ];
            isset($searchData['name']) && $whereParameter[] = [
                'name', 'like', $searchData['name']
            ];
        }

        return AdminUser::with(['role'])->where($whereParameter)->orderBy('id', 'desc')->paginate($perPage);
    }

    /**
     * 根据ID，返回管理员的模型数据
     * @param $id
     * @return mixed
     */
    public function getAdminUserObject($id){
        return AdminUser::find($id);
    }

    /**
     * 保存编辑管理员信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function save(Request $request){
        if(!$request->isMethod('post')){
            return $this->responseError('请求方式出错');
        }

        $postData = $request->post();
        $id = $request->input('id');
        $name = $postData['name'];
        $role_id = $postData['role_id'];
        $password = '123456';

        //编辑会员
        $adminUserObject = new AdminUser();

        if(!empty($id)){
            $adminUserObject = AdminUser::find($id);
            if(empty($adminUserObject)){
                return $this->responseError('编辑管理员不存在');
            }
            if(isset($adminUserObject->is_administrator['value']) && 1 == $adminUserObject->is_administrator['value']){
                return $this->responseError('超级管理员不能编辑');
            }
        }
        if($adminUserObject->name != $name){
            $validateName = AdminUser::Where('name', '=', $name)->first();
            if(!empty($validateName)){
                return $this->responseError('登录名【' . $name . '】已经存在');
            }
        }
        if(empty(RoleModel::find($role_id))){
            return $this->responseError('选择角色不存在');
        }

        $postData['is_administrator'] = 0;
        if(empty($id)){
            $postData['password'] = Hash::make($password, [$name, $password]);
        }

        try{
            if(empty($id)){
                $adminUserObject = $adminUserObject->create($postData);
                $id = $adminUserObject->id;
            } else {
                $adminUserObject->where('id', '=', $id)->update($postData);
            }
            return $this->responseSuccess(['id' => $id], '操作成功');
        } catch(\Exception $e){
            $errorMsg = $e->getMessage();
            $errorMsg = !empty($errorMsg) ? $errorMsg : '系统正在维护之中';
            return $this->responseError($errorMsg);
        }

    }

    /**
     * 权限验证
     * @param Request $request
     * @param $except
     * @return bool
     */
    public function validateAuthority(Request $request, $except){
        $sessionData = $request->session()->get('admin_user');

        //获取所有菜单
        $administratorRole = RoleModel::where('is_administrator', '=', 1)->first();
        if(empty($administratorRole) || empty($administratorRole->rule)){
            return true;
        }
        $request->session()->put('menuTree', $administratorRole->rule);

        //当前访问的路由别名
        $routeName = $request->route()->getName();
        if(empty($routeName)){
            return true;
        }

        //获取当前点击菜单以及其父的ID
        $currentMenuId = 0;
        $currentMenuFatherId = 0;
        foreach($administratorRole->rule as $firstKey=>$firstVal){
            if(!empty($firstVal['children'])){
                foreach($firstVal['children'] as $secondKey=>$secondVal){
                    if(isset($secondVal['url']['value']) && $secondVal['url']['value'] == $routeName){
                        $currentMenuId = $secondVal['id'];
                        break 2;
                    } else if(!empty($secondVal['children'])) {
                        foreach($secondVal['children'] as $thirdKey=>$thirdVal){
                            if(isset($thirdVal['url']['value']) && $thirdVal['url']['value'] == $routeName){
                                $currentMenuId = $thirdVal['id'];
                                $currentMenuFatherId = $thirdVal['father_id'];
                                break 3;
                            }
                        }
                    }
                }
            }
        }
        $request->session()->put('currentMenuId', $currentMenuId);
        $request->session()->put('currentMenuFatherId', $currentMenuFatherId);


        if(isset($sessionData['is_administrator']['value']) && 1 == $sessionData['is_administrator']['value']){
//            Log::channel('daily')->info('超级会员,不用验证');
            //超级管理员的权限
            $request->session()->put('adminUserRule', 'all');
            return true;
        }

        $adminUserObject = AdminUser::with(['role'])->find($sessionData['id']);
        if(empty($adminUserObject)){
            return false;
        }
        $adminUserObject = $adminUserObject->toArray();
        if(empty($adminUserObject['role']) || empty($adminUserObject['role']['rule']) || !is_array($adminUserObject['role']['rule'])){
            return false;
        }
        //管理员的权限
        $request->session()->put('adminUserRule', $adminUserObject['role']['rule']);

        $ruleData = array_flip($adminUserObject['role']['rule']);
        if(in_array($routeName, $except)){
//            Log::channel('daily')->info($routeName . '在允许通过之中');
            return true;
        }
        if(!empty($ruleData[$routeName])){
//            Log::channel('daily')->info($routeName . '规则允许之中');
            return true;
        } else {
//            Log::channel('daily')->info($routeName . '规则不允许通过');
            return false;
        }

    }
}
